﻿/* 14. *** Write a program that exchanges bits {p, p+1, …, p+k-1} 
 *                                   with bits {q, q+1, …, q+k-1} of given 32-bit unsigned integer. */

using System;

public class ExchangeSomeBits
{
    public static uint number;
    public static byte p;
    public static sbyte k;
    public static byte q;
    public static sbyte step;
    public static sbyte steps;
    public static sbyte direction;
    public static byte bitOfPSequence;
    public static byte bitOfQSequence;

    public static void Main()
    {
        DataInput();
        ExchangeBits();
    }

    public static void ExchangeBits()
    {
        for (int round = 0; round < steps; round++)
        {
            bitOfPSequence = (number | ((uint)1 << p)) == number ? (byte)1 : (byte)0;
            bitOfQSequence = (number | ((uint)1 << (p + step))) == number ? (byte)1 : (byte)0;
            if (bitOfPSequence == bitOfQSequence)
            {
                p = (byte)(p + direction);
                continue;
            }
            else if (bitOfPSequence == 1)
            {
                number &= ~((uint)1 << p);
                number |= ((uint)1 << (p + step));
            }
            else
            {
                number |= ((uint)1 << p);
                number &= ~((uint)1 << (p + step));
            }

            p = (byte)(p + direction);
        }

        Console.WriteLine("{1}\nnew number = {0}", number, string.Format(Convert.ToString(number, 2).PadLeft(32, '0')));
    }

    public static void DataInput()
    {
        do
        {
            Console.Clear();
            Console.Write("number = ");
            number = uint.Parse(Console.ReadLine());
            Console.WriteLine("{0}", string.Format(Convert.ToString(number, 2).PadLeft(32, '0')));
            Console.Write("p = ");
            p = byte.Parse(Console.ReadLine());
            Console.Write("k = ");
            k = sbyte.Parse(Console.ReadLine());
            Console.Write("q = ");
            q = byte.Parse(Console.ReadLine());
        } while ((p > 31) || (p + k - 1 < 0) || (p + k - 1 > 31) || (q > 31) || (q + k - 1 < 0) || (q + k - 1 > 31));
        
        if (k >= 0)
        {
            steps = (sbyte)(k + 1);
            direction = 1;
        }
        else
        {
            steps = (sbyte)(-k + 2);
            direction = -1;
        }

        step = (sbyte)(q - p);
    }
}